package org.road0329.dlt698.axdr;

import org.road0329.dlt698.ReverseByteArrayInputStream;
import org.road0329.dlt698.ReverseByteArrayOutputStream;
import org.road0329.dlt698.asn1.axdr.AxdrType;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.io.IOException;

public class OMD extends AxdrType {
    private byte[] dataCode = null;
    private Unsigned16 oi = null;
    private Unsigned8 mi = null;
    private Unsigned16 opm = null;

    public OMD() {
    }

    public byte[] getDataCode() {
        return dataCode;
    }

    public Unsigned16 getOi() {
        return oi;
    }

    public Unsigned8 getMi() {
        return mi;
    }

    public Unsigned16 getOpm() {
        return opm;
    }

    public void setDataCode(byte[] dataCode) {
        this.dataCode = dataCode;
    }

    public void setOmd(Unsigned16 oi, Unsigned8 mi, Unsigned16 opm) {
        this.oi = oi;
        this.mi = mi;
        this.opm = opm;
    }

    public int decode(ReverseByteArrayInputStream input) throws Exception {
        int codeLength = 0;
        this.oi = new Unsigned16();
        this.oi.setConst();
        codeLength += this.oi.decode(input);
        this.mi = new Unsigned8();
        this.mi.setConst();
        codeLength += this.mi.decode(input);
        this.opm = new Unsigned16();
        this.opm.setConst();
        codeLength += this.opm.decode(input);
        return codeLength;
    }

    public int encode(ReverseByteArrayOutputStream output) throws Exception {
        int codeLength = 0;
        if (this.dataCode != null) {
            codeLength = this.dataCode.length;
            for (int i = this.dataCode.length - 1; i >= 0; i--) {
                output.write(this.dataCode[i]);
            }
        } else {
            if (this.oi != null && this.mi != null && this.opm != null) {
                codeLength += this.opm.encode(output);
                codeLength += this.mi.encode(output);
                codeLength += this.oi.encode(output);
            } else {
                throw new IllegalArgumentException("oi, mi, or opm is null");
            }
        }
        return codeLength;
    }

    public void encodeAndSave(int encodingSizeGuess) throws Exception {
        ReverseByteArrayOutputStream revOStream = new ReverseByteArrayOutputStream();
        revOStream.setBufSize(encodingSizeGuess);
        this.encode(revOStream);
        this.dataCode = revOStream.toByteArray();
    }

    @Override
    public String toString() {
        if (this.oi != null && this.mi != null && this.opm != null) {
            return "sequence: {" + "oi: " + this.oi + ", mi: " + this.mi + ", opm: " + this.opm + "}";
        } else {
            return "oi, mi, or opm is null";
        }
    }
}



